from django.shortcuts import render
from django.http import HttpResponse
from system_app.dao import user_dao, check_task_dao
import requests
import uuid as create_uuid
from result.result_code import ajaxResult
import json
from common import logging
from common import idCardRecognition
from common import loadVideo, scanQRCode, putObject
from system_app.service import admin_user_service

# 小程序登录校验
def validation(request):
    # 小程序appid
    appid = "wx4a51f17d32846b0d"
    # 小程序secret
    secret = "4adfc53d7acce9076400bf9b4d410afa"
    # 获取用户请求code
    js_code = request.GET.get("js_code", "")
    grant_type = "authorization_code"

    # 请求头
    params = {
        "appid": appid,
        "secret": secret,
        "js_code": js_code,
        "grant_type": grant_type,
    }
    # 请求地址
    url = "https://api.weixin.qq.com/sns/jscode2session"
    weixin_obj = requests.get(url, params=params)

    openid = ""
    # 从微信服务器返回的结果中得到openid
    # openid = weixin_obj.openid
    # 定义返回信息
    res_info = {}
    user_info_dict = {}
    # errcode = 41002表示jscode无效
    res_json = weixin_obj.json()
    logging.info("weixin login result messate---->>>>" + str(res_json))
    errcode = res_json.get("errcode", 0)
    print(errcode)
    # errcode有很多错误码，
    if errcode in [41002, 40029, -1, 45011, 40226, 41008]:
        res_info["code"] = 2
        res_info["info"] = "jscode is invalid"
    else:
        openid = res_json.get("openid", "")
        # 设置返回dict
        user_info = user_dao.getUserInfo(openid)
        if user_info:
            user_info_dict["uuid"] = user_info.uuid
            user_info_dict["name"] = user_info.name
            user_info_dict["sex"] = user_info.sex
            user_info_dict["nation"] = user_info.nation
            user_info_dict["birth"] = user_info.birth
            user_info_dict["address"] = user_info.address
            user_info_dict["isValidate"] = user_info.isValidate
            user_info_dict["idCard"] = user_info.idCard
            user_info_dict["phone"] = user_info.phone
            user_info_dict["openid"] = user_info.openid
            data = {"data": user_info_dict}
            # 如果已经实名认证过，
            if user_info.isValidate == 1:
                res_info["code"] = 1
                res_info["info"] = "logged and validated"
                # 将用户信息返回
                res_info.update(data)
            else:
                res_info["code"] = 0
                res_info["info"] = "logged and unvalidated"
                # 将用户信息返回
                res_info.update(data)
        else:
            # 第一次登录
            res_info["code"] = -1
            res_info["info"] = "info:first login"
            # 将用户给的openid写入数据库中
            uuid = create_uuid.uuid4()
            user_dao.addUser({"uuid": uuid, "openid": openid})

    return HttpResponse(json.dumps(dict(res_info), indent=4))


# 实名认证
def real_name_auth(request):
    uuid = request.GET.get("uuid", "")
    # 查询用户是否实名认证
    user_info = user_dao.getUserInfoByUuid(uuid)
    res_info = {"code": 0, "info": "请重新上传身份证正反面图片"}
    if user_info:
        # 判断用户是否实名认证，1 为认证 0 为没有认证
        isValidate = user_info.isValidate
        # 如果没有进行身份校验
        if isValidate == 0:
            front_res = idCardRecognition.getIdCardInfo(
                uuid, "images/", "FRONT"
            )  # 识别身份证正面
            back_res = idCardRecognition.getIdCardInfo(
                uuid, "images/", "BACK"
            )  # 识别身份证反面
            if front_res["code"] == 1 and back_res["code"] == 1:
                data = front_res["data"]
                user_info_dic = {}
                user_info_dic["name"] = data["name"]
                user_info_dic["sex"] = data["sex"]
                user_info_dic["nation"] = data["nation"]
                user_info_dic["birth"] = data["birth"]
                user_info_dic["address"] = data["address"]
                user_info_dic["idCard"] = data["idCard"]
                user_info_dic["isValidate"] = 1
                res_info["code"] = 1
                res_info["info"] = "身份校验成功"
                # 并将用户信息插入到用户表中
                user_dao.updateUser(uuid, user_info_dic)
            elif front_res["code"] == 1:
                res_info["info"] = "请重新上传身份证反面图片"
            elif back_res["code"] == 1:
                res_info["info"] = "请重新上传身份证正面图片"
            else:
                res_info["info"] = "继续上传身份证图片"
        else:
            # 如果已经进行若身份校验
            res_info["info"] = "已身份校验"

    else:
        # 未查询到用户信息
        res_info["info"] = "error"
    return HttpResponse(json.dumps(res_info))


# 识别瓶身二维码
def scan_bottle_code(request):
    job_name = request.GET.get("job_name", "")
    # bottle code img path
    file_name = "images/" + job_name + "_bottle_code.jpg"
    fake_bottle_code = scanQRCode.scanQRCode(file_name)
    if fake_bottle_code == "":
        res_info = {"code": 1, "info": "识别失败", "bottle_code": fake_bottle_code}
    else:
        res_info = {"code": 0, "info": "识别成功", "bottle_code": fake_bottle_code}
    return HttpResponse(json.dumps(res_info))


# 添加检测任务
def addCheckTask(request):
    check_task_dic = {}
    res_info = {"code": "0", "info": "检测任务添加失败"}
    if request.method == "POST":
        body_unicode = request.body.decode("utf-8")
        params = json.loads(body_unicode)
        check_task_dic["uuid"] = params.get("task_uuid", "")
        check_task_dic["bottle_id"] = params.get("bottle_code", "")
        check_task_dic["video_url"] = params.get("video_url", "")
        check_task_dic["video_state"] = params.get("video_state", "0")
        check_task_dic["upload_time"] = params.get("upload_time", "0")
        check_task_dic["user_uuid"] = params.get("user_uuid", "0")
        check_task_dao.addCheckTask(check_task_dic)
        res_info["code"] = 1
        res_info["info"] = "检测任务添加成功"
    return HttpResponse(json.dumps(res_info))


# 查询视频检测状态
def getCheckTaskByUserUuid(request):
    res_info = {"code": "0", "info": "未查询到检测任务"}
    data = []
    ##任务状态 task_state: -1 表示视频不合格,0 表示审查中, 1 表示合格
    user_uuid = request.GET.get("user_uuid", "")
    check_task = check_task_dao.getCheckTaskByUserUuid(user_uuid)
    if check_task:
        for itr in check_task:
            res_info["code"] = 1
            res_info["info"] = "检测任务查询成功"
            info = {}
            info["uuid"] = itr.uuid
            info["video_url"] = itr.video_url
            info["upload_time"] = itr.upload_time
            info["video_state"] = itr.video_state
            info["check_result_state"] = itr.check_result_state
            info["user_uuid"] = itr.user_uuid
            data.append(info)
        res_info.update({"data": data})
    return HttpResponse(json.dumps(res_info))


# 获取用户信息
def getUserInfo(request):
    token = request.GET.get("token")
    user_info = {
        "data": {
            "roles": ["admin"],
            "avatar": "http://www.baidu.com",
            "introduction": "i am an user",
            "name": "user",
        }
    }
    return ajaxResult("success", user_info, "获取消息成功")


# 获取已经创建的检测任务中的视频列表
def getCheckVideoList(request):
    data_list = []
    res_data = {}
    checkVideoList = check_task_dao.getCheckVideoList()
    if checkVideoList:
        for itr in checkVideoList:
            dic = {}
            dic["id"] = itr.id
            dic["uuid"] = itr.uuid
            dic["video_state"] = itr.video_state
            dic["video_url"] = itr.video_url
            dic["bottle_id"] = itr.bottle_id
            dic["upload_time"] = itr.upload_time
            dic["video_state"] = itr.video_state
            dic["user_uuid"] = itr.user_uuid
            data_list.append(dic)
    res_data = {"data": data_list}
    return ajaxResult("success", res_data, "列表获取成功")


# 根据video_url获取对象存储视频url
def getVideoUrl(request):
    video_url = request.GET.get("video_url", default="")
    data = {}
    res_data = {"data": {}}
    video_url_s3 = loadVideo.getVideo(video_url)
    if video_url_s3:
        data["video_url_s3"] = video_url_s3
        res_data = {"data": data}
    return ajaxResult("success", res_data, "视频获取成功")


# 根据uuid获取检测人员身份证人脸信息
def getCheckTaskInfo(request):
    uuid = request.GET.get("uuid", 0)
    data = {}
    res_data = {"data": {}}
    # video_url_s3 = loadVideo.getVideo(video_url)
    video_url_s3 = ""
    if video_url_s3:
        data["video_url_s3"] = video_url_s3
        res_data = {"data": data}
    return ajaxResult("success", res_data, "视频获取成功")


# 根据检测任务uuid获取检测任务
def getCheckTaskByUuid(request):
    uuid = request.GET.get("uuid", 0)
    data = {}
    res_data = {}
    check_task_info = check_task_dao.getCheckTaskByUuid(uuid)
    if check_task_info:
        data["uuid"] = check_task_info.uuid
        data["bottle_id"] = check_task_info.bottle_id
        data["video_url"] = check_task_info.video_url
        data["upload_time"] = check_task_info.upload_time
        data["video_state"] = check_task_info.video_state
        data["user_uuid"] = check_task_info.user_uuid
        data["check_report_url"] = check_task_info.check_report_url
    res_data["data"] = data
    return ajaxResult("success", res_data, "检测任务获取成功")


# 更新检测视频审核状态
def updateVideoState(request):

    uuid = request.GET.get("params[0]", 0)
    video_state = request.GET.get("params[1]", 0)
    res = check_task_dao.updateVideoState(uuid, int(video_state))
    return ajaxResult("success", {}, "更新成功")


# 上传pdf
def uploadCheckResult(request):
    # body_unicode = request.body.decode("utf-8")
    up_file_list = request.FILES.getlist("file", None)
    putObject.upload("check_report/ddd.jpg", request.body)
    # for up_file in up_file_list:
    #     print(up_file)
    # return ajaxResult("success", {}, "更新成功")


# 系统后台登录
def login(request):
    data = {}
    user_name = request.GET.get("user_name")
    password = request.GET.get("password")
    res = admin_user_service.login(user_name, password)

    # 如果登录成功
    if res:
        data["token"] = "Admin-token"
        return ajaxResult("success", {"data": data}, "登录成功")

    return ajaxResult("error", {}, "用户名密码错误")


# 退出系统
def logout(request):

    return ajaxResult("success", None, "注销成功")
